package ripple.test.tools;

import ripple.common.entity.AbstractMessage;
import ripple.common.entity.NodeMetadata;
import ripple.server.core.Node;
import ripple.server.core.overlay.FicusOverlay;

import java.util.List;

public class DelayInjectTool {

    public static void setE2eDelay(int e2eDelay) {
        DelayInjectTool.e2eDelay = e2eDelay;
    }

    public static void setE2cDelay(int e2cDelay) {
        DelayInjectTool.e2cDelay = e2cDelay;
    }

    public static void setC2cDelay(int c2cDelay) {
        DelayInjectTool.c2cDelay = c2cDelay;
    }

    private static int e2eDelay = 10;
    private static int e2cDelay = 100;
    private static int c2cDelay = 10;

    public static void inject(AbstractMessage message, Node node) throws Exception {
        Thread.sleep(getDelay(node.getNodeList(), message.getLastUpdateServerId(), node.getId()));
    }

    public static int getDelay(List<NodeMetadata> nodeList, int id1, int id2) throws Exception {
        int groupId1 = id1 / FicusOverlay.MAX_SERVER_COUNT;
        int groupId2 = id2 / FicusOverlay.MAX_SERVER_COUNT;

        if (id1 == 0 || id2 == 0) {
            return 0;
        } else if (id1 < 10 && id2 < 10) {
            return c2cDelay;
        } else if (id1 > 10 && id2 > 10) {
            return e2eDelay;
        } else {
            return e2cDelay;
        }

//        int groupId1 = -1;
//        int groupId2 = -1;
//        for(NodeMetadata node : nodeList) {
//            if (node.getId() == id1) {
//                groupId1 = node.getGroupId();
//            }
//            if (node.getId() == id2) {
//                groupId2 = node.getGroupId();
//            }
//            if (groupId1 != -1 && groupId2 != -1) {
//                break;
//            }
//        }
//        if (groupId1 == -1 || groupId2 == -1) {
//            throw new Exception();
//        }
//        int delay;
//        if (groupId1 == groupId2) {
//            delay = 10;
//        } else {
//            delay = 100;
//        }
//        return delay;
    }
}
